﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using AMM.Model;
using AMM.Model.Store;

namespace AMM.DataAccess.Store {
    public class OutStoreOrderRepository : BaseRepository<OutStoreOrder> {

        private int _pageSize;

        public OutStoreOrderRepository(int pageSize = int.MaxValue) {
            this._pageSize = pageSize;
        }

        public OutStoreOrder FetchOutStoreOrderById(int outStoreOrderId) {
            using (var ctx = this.Context) {
                return ctx.OutStoreOrders
                    .Include("Basic")
                    .Include("OutStoreOrderDetails")
                    .FirstOrDefault(x => x.OutStoreOrderId == outStoreOrderId);
            }
        }

        public OutStoreOrder FetchOutStoreOrderByIdForView(int outStoreOrderId) {
            using (var ctx = this.Context) {
                return ctx.OutStoreOrders
                    .Include("OutStoreOrderDetails")
                    .Include("OutStoreOrderDetails.Material")
                    .Include("OutStoreOrderDetails.Material.Basic1")
                    .FirstOrDefault(x => x.OutStoreOrderId == outStoreOrderId);
            }
        }

        public List<OutStoreOrderDetail> FetchMaterialViewModelListByOutStoreOrderId(int outStoreOrderId) {
            using (var ctx = this.Context) {
                return ctx.OutStoreOrderDetails
                    .Include("Material")
                    .Include("Material.Basic")
                    .Where(x => x.OutStoreOrderId == outStoreOrderId).ToList();
            }
        }

        public void InsertOutStoreOrder(OutStoreOrder outStoreOrder) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        // Subtract store amount
                        outStoreOrder.OutStoreOrderDetails.ToList().ForEach(x => {
                            List<MaterialStore> existMSList = ctx.MaterialStores
                                .Where(y => y.MaterialId == x.MaterialId)
                                .OrderBy(y => y.Quantity)
                                .ToList();

                            decimal tempOfQuantity = x.Quantity, restOfQuantity = x.Quantity;
                            foreach (MaterialStore ms in existMSList) {
                                tempOfQuantity = tempOfQuantity - ms.Quantity;
                                if (tempOfQuantity > 0) {
                                    ms.OutStoreTotal += ms.Quantity;
                                    ms.Quantity = 0;
                                    ctx.MaterialStores.Attach(ms);
                                    ctx.Entry(ms).State = EntityState.Modified;
                                    restOfQuantity = tempOfQuantity;
                                }
                                else {
                                    ms.Quantity -= restOfQuantity;
                                    ms.OutStoreTotal += restOfQuantity;
                                    ctx.MaterialStores.Attach(ms);
                                    ctx.Entry(ms).State = EntityState.Modified;
                                    break;
                                }
                            }
                        });

                        ctx.OutStoreOrders.Add(outStoreOrder);
                        ctx.Entry(outStoreOrder).State = EntityState.Added;

                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public void UpdateOutStoreOrder(OutStoreOrder outStoreOrder) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        outStoreOrder.OutStoreOrderDetails.Where(x => x.ClassStatus == ClassStatus.Added).ToList().ForEach(x => {
                            x.OutStoreOrder = outStoreOrder;
                            x.OutStoreOrderId = outStoreOrder.OutStoreOrderId;
                            x.OutStoreOrderDetailsId = Guid.NewGuid().GetHashCode();
                        });
                        // do not try to merge with above codes, because you can't change the fields which was marked as primary key
                        outStoreOrder.OutStoreOrderDetails.ToList().ForEach(x => {
                            ctx.OutStoreOrderDetails.Attach(x);
                            switch (x.ClassStatus) {
                                case ClassStatus.UnChanged:
                                    ctx.OutStoreOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Unchanged;
                                    break;
                                case ClassStatus.Updated:
                                    x.ModifiedBy = outStoreOrder.ModifiedBy;
                                    x.ModifiedDatetime = DateTime.Now;
                                    ctx.OutStoreOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Modified;
                                    break;
                                case ClassStatus.Added:
                                    x.CreatedBy = outStoreOrder.ModifiedBy;
                                    x.CreatedDatetime = DateTime.Now;
                                    ctx.OutStoreOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Added;
                                    break;
                                case ClassStatus.Deleted:
                                    ctx.OutStoreOrderDetails.Attach(x);
                                    ctx.Entry(x).State = EntityState.Deleted;
                                    break;
                            }
                        });

                        ctx.OutStoreOrders.Attach(outStoreOrder);
                        ctx.Entry(outStoreOrder).State = EntityState.Modified;

                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public void DeleteMultipleOutStoreOrder(params int[] outStoreOrderIds) {
            using (var ctx = this.Context) {
                using (DbContextTransaction trans = ctx.Database.BeginTransaction()) {
                    try {
                        ctx.OutStoreOrderDetails.Where(x => outStoreOrderIds.Contains(x.OutStoreOrderId)).ToList().ForEach(x => {
                            ctx.OutStoreOrderDetails.Remove(x);
                        });
                        ctx.OutStoreOrders.Where(x => outStoreOrderIds.Contains(x.OutStoreOrderId)).ToList().ForEach(x => {
                            ctx.OutStoreOrders.Remove(x);
                        });
                        ctx.SaveChanges();
                        trans.Commit();
                    }
                    catch (Exception ex) {
                        trans.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public List<OutStoreOrder> FetchOutStoreOrderList(OutStoreOrderSearchModel searchModel, int pageIndex) {
            using (var ctx = this.Context) {
                var query = ctx.OutStoreOrders
                    .Include("ProduceConduct")
                    .Include("Basic")
                    .Include("Basic1")
                    .Include("OutStoreOrderDetails")
                    .Include("OutStoreOrderDetails.Material")
                    .Where(x => !string.IsNullOrEmpty(x.Code));

                if (!string.IsNullOrEmpty(searchModel.OutStoreOrderCode)) {
                    query = query.Where(x => x.Code.Contains(searchModel.OutStoreOrderCode));
                }
                if (!string.IsNullOrEmpty(searchModel.ProduceConductCode)) {
                    query = query.Where(x => x.ProduceConduct.Code.Contains(searchModel.ProduceConductCode));
                }
                if (!string.IsNullOrEmpty(searchModel.MaterialCode)) {
                    query = query.Where(x => x.OutStoreOrderDetails.Any(y => y.Material.Code.Contains(searchModel.MaterialCode)));
                }
                if (searchModel.OutStoreDateStart.HasValue) {
                    query = query.Where(x => x.OutStoreOrderDetails.Any(y => y.CreatedDatetime >= DbFunctions.TruncateTime(searchModel.OutStoreDateStart.Value)));
                }
                if (searchModel.OutStoreDateEnd.HasValue) {
                    query = query.Where(x => x.OutStoreOrderDetails.Any(y => y.CreatedDatetime <= DbFunctions.TruncateTime(searchModel.OutStoreDateEnd.Value)));
                }
                if (searchModel.MaterialOutStoreTypeId.HasValue) {
                    query = query.Where(x => x.OutStoreTypeId == searchModel.MaterialOutStoreTypeId.Value);
                }

                searchModel.Records = query.Count();
                pageIndex = (pageIndex - 1) * this._pageSize > searchModel.Records ? 1 : pageIndex;

                return query.OrderByDescending(x => x.CreatedDatetime).Skip((pageIndex - 1) * this._pageSize).Take(this._pageSize).ToList();
            }
        }

        public int GetTheMaxFlowNumber(string startString) {
            using (var ctx = this.Context) {
                OutStoreOrder outStoreOrder = ctx.OutStoreOrders
                    .Where(x => x.Code.StartsWith(startString))
                    .OrderByDescending(x => x.Code)
                    .FirstOrDefault();
                int maxFlowNumber = outStoreOrder == null
                    ? 0
                    : Convert.ToInt32(outStoreOrder.Code.Substring(outStoreOrder.Code.Length - 2, 2));
                return Math.Max(ctx.OutStoreOrders.Count(x => x.Code.StartsWith(startString)), maxFlowNumber);
            }
        }
    }
}
